/* 2. 添加新书 */
'use strict';

const CHECK = require('../myUtil/formatCheck');
const db = require('../../coSqlite3');
const HTM = require('../myUtil/lib').html;

exports.addNewBook = function* (req, res) {
    console.log("----------------------2. 添加新书\n");
    let bID = req.body.bID;
    let bName = req.body.bName;
    let bPub = req.body.bPub;
    let bDate = req.body.bDate;
    let bAuthor = req.body.bAuthor;
    let bMem = req.body.bMem;
    let bCnt = req.body.bCnt;

    let htm = HTM.divBegin + 2 + HTM.divEnd + '提交的参数有误：';
    if (bID == '') {
        return HTM.begin + htm + '书号不能为空' + HTM.end;
    } else if (bID.length > 30) {
        return HTM.begin + htm + '书号长度不能超过30' + HTM.end;
    }

    if (bName == '') {
        return HTM.begin + htm + '书名不能为空' + HTM.end;
    } else if (bName.length > 30) {
        return HTM.begin + htm + '书名长度不能超过30' + HTM.end;
    }

    if (bPub.length > 30) {
        return HTM.begin + htm + '出版社长度不能超过30' + HTM.end;
    }   

    if (bDate != '') {
        if (!CHECK.dataFormatCheck(bDate)) {
            return HTM.begin + htm + '出版日期格式不正确' + HTM.end;
        }
    }

    if (bAuthor.length > 20) {
        return HTM.begin + htm + '作者长度不能超过20' + HTM.end;
    }

    if (bMem.length > 30) {
        return HTM.begin + htm + '内容摘要长度不能超过30' + HTM.end;
    }

    if (bCnt == '') {
        return HTM.begin + htm + '数量不能为空' + HTM.end;
    } else if (!CHECK.isNumber(bCnt)) {
        return HTM.begin + htm + '数量必须是数字' + HTM.end;
    } else if (bCnt <= 0) {
        return HTM.begin + htm + '数量必须大于0' + HTM.end;
    }



    htm = HTM.divBegin + 1 + HTM.divEnd;
    try {
        let exist = yield db.execSQL('SELECT count(bID) as count FROM book WHERE bID = ?', [bID]);
        if (exist[0].count > 0) {
            return HTM.begin + htm + '该书已经存在' + HTM.end;
        }
        let rows = yield db.execSQL('insert into book values(?,?,?,?,?,?,?,?)', [bID, bName, bPub, bDate, bAuthor, bMem, bCnt, bCnt]);
    } catch (err) {
        htm = HTM.divBegin + 3 + HTM.divEnd + "数据库执行失败: ";
        return HTM.begin + htm +  err + HTM.end;
    }

    htm = HTM.divBegin + 0 + HTM.divEnd;
    
    return HTM.begin + htm + '成功' + HTM.end;
}